import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { addCartService, getCartListService, deleteCartService } from '@/api/cart'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore(
  'cart',
  () => {
    const userStore = useUserStore()
    const isLogin = userStore.userInfo.token //判断是否登录

    // 1.state数据
    const cartList = ref([])
    // 2.actions方法

    // 获取购物车列表
    const getCartList = async () => {
      const res = await getCartListService()
      cartList.value = res.data.result
    }

    // 添加购物车商品
    const addCart = async (goods) => {
      const { skuId, count } = goods
      if (isLogin) {
        console.log('已登录')
        //已登录
        await addCartService({ skuId, count })

        getCartList()
        ElMessage.success('添加购物车成功')
      } else {
        console.log('未登录')

        //未登录
        //购物车中存在
        const item = cartList.value.find((e) => e.skuId == goods.skuId)
        if (item) {
          //cartList.value中存在
          item.count += goods.count
        } else {
          cartList.value.push(goods)
        }
      }
    }

    // 删除购物车商品
    // findIndex函数 的返回值：
    // （1）返回第一个满足条件的元素的索引。
    // （2）如果没有找到满足条件的元素，返回 -1
    const removeCart = async (skuId) => {
      if (isLogin) {
        //已登录
        await deleteCartService([skuId])
        getCartList()
        // 提示消息
        ElMessage.warning('删除商品成功')
      } else {
        //未登录
        const idx = cartList.value.findIndex((e) => e.skuId === skuId) //寻找索引
        cartList.value.splice(idx, 1) //删除对应项
      }
    }

    // 单选框： 修改购物车商品状态
    const singleCheck = (skuId, selected) => {
      const item = cartList.value.find((e) => e.skuId === skuId)
      item.selected = selected
    }

    // 全选框：
    const isAll = computed(() => cartList.value.every((e) => e.selected)) //单选 决定 全选
    const allCheck = (selected) => {
      //全选 决定 所有单选框
      cartList.value.forEach((e) => (e.selected = selected))
    }

    // 选中 总数
    const checkedCount = computed(() =>
      cartList.value.filter((e) => e.selected).reduce((sum, e) => sum + e.count, 0),
    )
    // 选中 总价
    const checkedPrice = computed(() =>
      cartList.value.filter((e) => e.selected).reduce((sum, e) => sum + e.count * e.price, 0),
    )
    // 购物车 总数
    const allCount = computed(() => cartList.value.reduce((sum, e) => sum + e.count, 0))
    // 购物车 总价
    const allPrice = computed(() => cartList.value.reduce((sum, e) => sum + e.count * e.price, 0))

    // 清空购物车列表 并 清楚登录状态
    const clearCartList = () => {
      // console.log('清空完毕')
      cartList.value = []

      // console.log('登录状态：' + isLogin)
      // console.log('token状态：' + userStore.userInfo.token)
    }

    // 暴露出去
    return {
      cartList,
      allCount,
      allPrice,
      isAll,
      checkedCount,
      checkedPrice,
      getCartList,
      addCart,
      removeCart,
      singleCheck,
      allCheck,
      clearCartList,
    }
  },
  {
    persist: true, //持久化
  },
)
